package com.jiajia.study.nio.chapter01;

import java.nio.ByteBuffer;

public class TestNio06{
    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put(new byte[]{'a','b','c','d'});
        // 切换成读模式
        byteBuffer.flip();

        System.out.println("data is : " + (char)byteBuffer.get());
        System.out.println("data is : " + (char)byteBuffer.get());
        System.out.println("position is : " + byteBuffer.position() + " limit is : " + byteBuffer.limit() + " capacity is  : " + byteBuffer.capacity());

        // 标记当前读的位置
        byteBuffer.mark();
        System.out.println("data is : " + (char)byteBuffer.get());
        System.out.println("data is : " + (char)byteBuffer.get());
        System.out.println("before reset ---->  position is : " + byteBuffer.position() + " limit is : " + byteBuffer.limit() + " capacity is  : " + byteBuffer.capacity());
        /**
         * 可以用  mark  reset 实现 rewind 的方法，
         *  rewind 每次都重置  position 为 0
         *  mark reset 更加灵活
         */
        // 重新回到标记的位置
        byteBuffer.reset();
        System.out.println("after reset ---->  position is : " + byteBuffer.position() + " limit is : " + byteBuffer.limit() + " capacity is  : " + byteBuffer.capacity());
        // 重复读取
        System.out.println("data is : " + (char)byteBuffer.get());
        System.out.println("data is : " + (char)byteBuffer.get());

        byteBuffer.reset();
        System.out.println("after reset ---->  position is : " + byteBuffer.position() + " limit is : " + byteBuffer.limit() + " capacity is  : " + byteBuffer.capacity());
        // 重复读取
        System.out.println("data is : " + (char)byteBuffer.get());
        System.out.println("data is : " + (char)byteBuffer.get());
    }
}
